package com.tads.torry.messagecenter.facade;

import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import cn.hutool.extra.template.engine.velocity.VelocityEngine;
import cn.hutool.extra.template.engine.velocity.VelocityTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tads.torry.messagecenter.domain.accessor.MessageSenderAccessor;
import com.tads.torry.messagecenter.domain.accessor.MessageTemplateAccessor;
import com.tads.torry.messagecenter.domain.accessor.TenantAccessor;
import com.tads.torry.messagecenter.domain.enums.ChannelType;
import com.tads.torry.messagecenter.domain.enums.UserStatus;
import com.tads.torry.messagecenter.domain.model.MessageSender;
import com.tads.torry.messagecenter.domain.model.MessageTemplate;
import com.tads.torry.messagecenter.domain.model.Tenant;
import com.tads.torry.messagecenter.domain.renderer.VelocityTemplateRenderer;
import com.tads.torry.messagecenter.domain.service.IMessageSender;
import com.tads.torry.messagecenter.facade.dto.TemplateMsgDTO;
import com.tads.torry.messagecenter.infras.entity.MessageTemplateDO;
import com.tads.torry.messagecenter.infras.mapper.TenantMapper;
import com.zen.boot.common.exception.BizException;
import com.zen.boot.common.exception.enums.CommonExceptionEnum;
import com.zen.boot.common.util.Preconditions;
import org.apache.poi.ss.formula.functions.T;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
public class MessageFacade {
    private static final Map<String, IMessageSender> MESSAGE_SENDER_BEANS = new HashMap<>();

    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    private void cacheMsgSenderBeans() {
        Map<String, IMessageSender> beansMap = applicationContext.getBeansOfType(IMessageSender.class);
        beansMap.values().forEach(bean -> {
            com.tads.torry.messagecenter.domain.anno.MessageSender sender = bean.getClass().getDeclaredAnnotation(com.tads.torry.messagecenter.domain.anno.MessageSender.class);
            if (sender != null) {
                MESSAGE_SENDER_BEANS.put(sender.channel().name(), bean);
            }
        });
    }

    @Resource
    private TenantAccessor tenantAccessor;

    @Resource
    private MessageTemplateAccessor messageTemplateAccessor;

    @Resource
    private MessageSenderAccessor messageSenderAccessor;

    public boolean sendTemplateMsg(TemplateMsgDTO dto) {
        Tenant tenant = tenantAccessor.getByApiKey(dto.getApiKey());
        if (tenant == null || tenant.getStatus().equals(UserStatus.INACTIVE)) {
            return false;
        }

        MessageTemplate template = messageTemplateAccessor.getById(dto.getTemplateId());
        if (template == null || !template.getTenantId().equals(tenant.getId())) {
            return false;
        }

        if (!dto.getUseDefaultReceivers()) {
            Preconditions.ofNotEmpty(dto.getReceivers(), CommonExceptionEnum.ILLEGAL_ARGUMENT);
            Preconditions.ofNotNull(dto.getReceiverType(), CommonExceptionEnum.ILLEGAL_ARGUMENT);
        } else {
            Preconditions.ofNotEmpty(template.getDefaultReceivers(), CommonExceptionEnum.ILLEGAL_ARGUMENT);
            Preconditions.ofNotNull(template.getDefaultReceiverType(), CommonExceptionEnum.ILLEGAL_ARGUMENT);
        }

        Integer defaultSenderId = template.getDefaultSenderId();
        MessageSender sender = messageSenderAccessor.getById(defaultSenderId);
        ChannelType channelType = sender.getChannelType();

        IMessageSender messageSender = MESSAGE_SENDER_BEANS.get(channelType.name());

        String content = VelocityTemplateRenderer.doRender(template.getContent(), dto.getContentParams());
        String title = VelocityTemplateRenderer.doRender(template.getTitle(), dto.getTitleParams());

        messageSender.send();
        return true;
    }

    public static void main(String[] args) {
        // 初始化 Velocity 引擎
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setResourceMode(TemplateConfig.ResourceMode.STRING);
        TemplateEngine engine = TemplateUtil.createEngine(templateConfig);
        Template msgTemplate = engine.getTemplate("Hello, $name!");
        Map<String,Object> contentParams = new HashMap<>();
        contentParams.put("name", "torry wang");
        String render = msgTemplate.render(contentParams);
        System.out.println(render);
    }
}
